<?php

namespace App\Http\Controllers\Front;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Interfaces\AddressService;
use App\Exceptions\Front\AddressException;
use Auth;
use App\Http\Requests\Front\address\AddAddressRequest;
use App\Http\Requests\Front\address\UpdateAddressRequest;
use Log;

class MyAddressController extends Controller
{

    public function index(AddressService $addressService)
    {
        $user = Auth::user();

        if($user){
            $user_id = $user->id;

        }else{

            throw new AddressException("收货人参数不能为空，请登录");
        }//end if()

        $addressInfo = $addressService->getAddressInfo($user_id);

        return view('front.my.address', compact('addressInfo'));
    }


    public function create(AddAddressRequest $addressRequest, AddressService $addressService){

        $user = Auth::user();

        if($user){
            $user_id = $user->id;

        }else{

            throw new AddressException("收货人参数不能为空，请登录");
        }//end if()


        $addressArr = [];
        $addressArr = $addressRequest->all();
        if(empty($addressArr)){

            throw new AddressException("要创建的收货地址字段信息不能为空");

        }//end if()


        $address_id = $addressService->addAddress($user_id, $addressArr);

        return Response()->json(['status'=>1, 'address_id'=>$address_id]);
    }//end func create

    /**
     * 删除收货地址
     * @param $address_id      收货地址id
     * @return mixed
     */
    public function destroy($address_id, AddressService $addressService){

        if(empty($address_id)){

            throw new AddressException("要删除的收货地址id不能为空");

        }//end if()

        $addressObj = $addressService->removeAddress($address_id);

        return Response()->json(['status'=>1]);
    }//end func destory


    /**
     * 修改收货地址
     * @param int $address_id     收货地址id
     * @param array $addressArr   要修改的收货地址信息数组
     * @return mixed
     */
    public function update($address_id, UpdateAddressRequest $updateAddressRequest, AddressService $addressService){

        if(empty($address_id)){

            throw new AddressException("要修改的收货地址id不能为空");

        }//end if()

        $addressArr = $updateAddressRequest->all();
        if(empty($addressArr)){

            throw new AddressException("要修改的收货地址信息字段不能为空");

        }//end if()

        $addressObj = $addressService->updateAddress($address_id, $addressArr);

        return Response()->json(['status'=>1]);

    }//end  func updateAddress

}
